﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using InfoSource.Data;
using InfoSource.Models.objects;
using System.Diagnostics;

namespace InfoSource.Models
{
	public class ZipCodeContratractorsModel
	{
		#region Properties ======================================================================

		public int ZipCode;
		public IEnumerable<Contractor> Contractors { get; set; }
		public IEnumerable<Contractor> ServicePlanHVACContractors
		{
			get
			{
				if (Contractors == null) SetContractors();

				return Contractors.Where(c => c.DoesServicePlanHVAC == true);
			}
		}

		public IEnumerable<Contractor> ServicePlanApplianceContractors
		{
			get
			{
				if (Contractors == null) SetContractors();

				return Contractors.Where(c => c.DoesServicePlanAppliances == true);
			}
		}

		public IEnumerable<Contractor> BrokeringHVACContractors
		{
			get
			{
				if (Contractors == null) SetContractors();

				return Contractors.Where(c => c.DoesBrokeringHVAC == true);
			}
		}

		public IEnumerable<Contractor> BrokeringApplianceContractors
		{
			get
			{
				if (Contractors == null) SetContractors();

				return Contractors.Where(c => c.DoesBrokeringAppliances == true);
			}
		}

		public IEnumerable<Contractor> MiscellaneousContractors
		{
			get
			{
				if (Contractors == null) SetContractors();

				return Contractors.Where(c => c.DoesMiscellaneous == true);
			}
		}


		private InfoSourceDB _infoSourceDB { get; set; }

		#endregion

		#region Constructor =====================================================================

		public ZipCodeContratractorsModel()
		{
			_infoSourceDB = new InfoSourceDB();
		}

		public ZipCodeContratractorsModel(int zipCode)
			: this()
		{
			this.ZipCode = zipCode;

			SetContractors();
		}

		#endregion

		#region Methods =========================================================================

		public void SetContractors()
		{
			var areasServed = _infoSourceDB.v_Ins_and_Sec_Areas_Served_ZipCode
				.Where(areaServed => areaServed.zip == this.ZipCode).ToList();

			var activeContractors = _infoSourceDB.v_Ins_and_Sec_Contractors
				.Where(c => c.Status == "ACTIVE").ToList();

			List<Contractor> contractors = new List<Contractor>();

			foreach (v_Ins_and_Sec_Areas_Served_ZipCode asz in areasServed)
			{
				v_Ins_and_Sec_Contractors dbContractor = activeContractors.FirstOrDefault(c => c.Code == asz.code);

				if (dbContractor != null)
				{
					Contractor contractor = new Contractor();
					contractor = contractor.ConvertFromDBObject(dbContractor);

					contractors.Add(contractor);
				}
			}

			this.Contractors = contractors.OrderByDescending(c => c.Rank);

		}

		#endregion
	}
}